/**
 * 
 */
package com.yi.user.internal.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.yi.model.db.mongo.MongoDBHelper;
import com.yi.model.internal.impl.ModelApi;
import com.yi.model.objects.DBDefinitions;
import com.yi.role.objects.Role;
import com.yi.user.internal.IUserApi;
import com.yi.user.objects.User;

/**
 * @author long
 *
 */
public class UserApi extends ModelApi implements IUserApi {

	private MongoDBHelper dbHelper;
	/* (non-Javadoc)
	 * @see com.yi.role.internal.IUserApi#create(com.yi.role.objects.User)
	 */
	public String create(User user) {
		// TODO Auto-generated method stub
		return getDbHelper().addEntity(DBDefinitions.userColl, convertUserToEntity(user));
	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IUserApi#view(java.lang.String)
	 */
	public User view(String id) {
		// TODO Auto-generated method stub
		return convertEntityToUser(dbHelper.viewEntityById(DBDefinitions.userColl, id));
	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IUserApi#update(com.yi.role.objects.User)
	 */
	public void update(User user) {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IUserApi#delete(java.lang.String)
	 */
	public void delete(String id) {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see com.yi.role.internal.IUserApi#list()
	 */
	public List<User> list(int pageNumber) {
		// TODO Auto-generated method stub
		List<DBObject> matches = dbHelper.findEntities(DBDefinitions.userColl, pageNumber);
		List<User> users = new ArrayList<User>();
		for(DBObject entity : matches){
			users.add(convertEntityToUser(entity));
		}
		return users;
	}
	
	private DBObject convertUserToEntity(User user){
		DBObject entity = convertModelToEntity(user);
		entity.put(DBDefinitions.col_roleId, user.roleId);
		entity.put(DBDefinitions.col_email, user.email);
		return entity;
	}

	private User convertEntityToUser(DBObject entity){
		User user =  new User(convertEntityToModel(entity));
		user.email = entity.get(DBDefinitions.col_email).toString();
		user.roleId = entity.get(DBDefinitions.col_roleId).toString();
		return user;
	}
	
	public MongoDBHelper getDbHelper() {
		return dbHelper;
	}

	public void setDbHelper(MongoDBHelper dbHelper) {
		this.dbHelper = dbHelper;
	}

}
